package com.cqupt.sendMes.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
@Configuration
public class EncryptUtils {
    /**
     * AES加解密工具
     * */

    // AES密钥算法
    private static final String KEY_ALGORITHM = "AES";

    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    @Value("${encrypt.AESKey}")
    private String key;

    // 生成密钥
    public static String generateAESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(128, new SecureRandom()); // 192 and 256 bits may not be available
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }
    public String encryptAES(String data) {
        try{
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e){
            log.error(e.getMessage());
            return null;
        }
        //AES加密
    }


    // AES解密
    public String decryptAES(String data) {
        try{
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(data));
            return new String(decrypted);
        } catch (Exception e){
            log.error(e.getMessage());
            return null;
        }

    }


//    public static void main(String[] args) throws Exception {
////        String key = generateAESKey();
//        String originalText = "";
//        String encryptedText = encryptAES(originalText);
//        String decryptedText = decryptAES(encryptedText);
//
//        System.out.println("Original Text: " + originalText);
//        System.out.println("Encrypted Text: " + encryptedText);
//        System.out.println("Decrypted Text: " + decryptedText);
//    }
}
